package com.joolun.weixin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joolun.system.domain.StaffDepartment;
import com.joolun.system.mapper.ScrmDepartmentMapper;
import com.joolun.weixin.mapper.StaffDepartmentMapper;
import com.joolun.weixin.service.IStaffDepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author xxh
 * @since 2021-12-16
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class StaffDepartmentServiceImpl extends ServiceImpl<StaffDepartmentMapper, StaffDepartment> implements IStaffDepartmentService {


    @Autowired
    private ScrmDepartmentMapper scrmDepartmentMapper;

    @Override
    public void removeByStaffIds(List<Long> staffIds) {
        if (CollectionUtil.isNotEmpty(staffIds)) {
            remove(new LambdaQueryWrapper<StaffDepartment>().in(StaffDepartment::getStaffId, staffIds));
        }
    }

    @Override
    public void removeByDepartmentIds(List<Long> departmentIds) {
        if (CollectionUtil.isNotEmpty(departmentIds)) {
            remove(new LambdaQueryWrapper<StaffDepartment>().in(StaffDepartment::getDepartmentId, departmentIds));
        }
    }

    @Override
    public Long queryDepartmentStaffNum(String extCorpId, Long extId) {
        List<Long> extDepartmentIds = null;

        //如果是不是根部门递归查出子部门列表
        if (!Objects.equals(1L, extId)) {
//            extDepartmentIds = departmentService.getChildIdList(extCorpId, Collections.singletonList(extId));
            extDepartmentIds = this.getChildIdList(extCorpId, Collections.singletonList(extId),new ArrayList<>());

        }

        return baseMapper.queryDepartmentStaffNum(extCorpId, extDepartmentIds);
    }

    public List<Long> getChildIdList(String extCorpId, List<Long> extParentIdList, List<Long> childIdList) {
        if (CollectionUtil.isNotEmpty(extParentIdList)) {
            List<Long> result = this.scrmDepartmentMapper.queryChildIdList(extCorpId, extParentIdList);
            if (CollectionUtil.isNotEmpty(result)) {
                childIdList.addAll(result);
                // 递归调用当前方法，直至获取所有子级id集合
                getChildIdList(extCorpId, result, childIdList);
            }
        }
        childIdList.addAll(extParentIdList);
        return childIdList.stream().distinct().collect(Collectors.toList());
    }
}
